import java.io.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


@SuppressWarnings("serial")
public class AdminItemServlet extends HttpServlet{

	private Namespace nameSpace = Namespace.getNamespace("http://www.cs.au.dk/dWebTek/2011");

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Document itemXmlFromCloud;
		PrintWriter out = response.getWriter();

		try {
			itemXmlFromCloud = new SAXBuilder().build("http://services.brics.dk/java/cloud/listItems?shopID=16");
			List<Element> items = itemXmlFromCloud.getRootElement().getChildren("item", nameSpace);
			buildTable(out, items);

		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}

	private void buildTable(PrintWriter out, List<Element> items) throws IOException 
	{
		//define top lvl table element (root)
		Element table = new Element("table");
		table.setAttribute("border", "1");

		//create doc with table as root element
		Document itemsXml = new Document(table);


		//define titels for tabel
		{
			Element tr = new Element("tr");
			table.addContent(tr);

			Element td = new Element("th"); //itemnr
			td.setText("ItemID");
			tr.addContent(td);

			td = new Element("th"); //name
			td.setText("Movie Name");
			tr.addContent(td);

			td = new Element("th"); //Stock
			td.setText("Stock");
			tr.addContent(td);
		}

		for(Element item : items){
			//row
			Element tr = new Element("tr");
			table.addContent(tr);

			//item name
			Element td = new Element("td");
			td.setText(	item.getChildText("itemID", nameSpace)	);
			tr.addContent(td);

			//item number
			td = new Element("td");
			td.setText(	item.getChildText("itemName", nameSpace)	);
			tr.addContent(td);

			//item stock
			td = new Element("td");
			td.setText(	item.getChildText("itemStock", nameSpace)	);
			tr.addContent(td);
		}

		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
		outputter.output(itemsXml, out);
	}
}